export class DialogueAnalysisWebSocket {
  private ws: WebSocket | null = null;
  private messageCallback: ((message: string) => void) | null = null;
  private errorCallback: ((error: string) => void) | null = null;
  private openCallback: (() => void) | null = null;

  constructor(private url: string = 'wss://xyz.wwh-ai-sites.xin/trae_dialogue_analyze/') {}

  connect() {
    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      if (this.openCallback) {
        this.openCallback();
      }
      console.log('WebSocket connection established');
    };

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (this.messageCallback) {
          // 处理不同类型的消息
          if (data.type === 'response') {
            this.messageCallback(data.content);
          } else if (data.type === 'analysis') {
            // 处理分析结果
            this.messageCallback(data.analysis);
          } else if (data.type === 'error') {
            if (this.errorCallback) {
              this.errorCallback(data.error);
            }
          } else {
            // 如果没有特定类型，直接返回内容
            this.messageCallback(data.content || event.data);
          }
        }
      } catch (error) {
        // 如果不是JSON格式，直接返回原始消息
        if (this.messageCallback) {
          this.messageCallback(event.data);
        }
      }
    };

    this.ws.onerror = (error) => {
      if (this.errorCallback) {
        this.errorCallback('WebSocket connection error');
        console.error('WebSocket error:', error);
      }
    };

    this.ws.onclose = () => {
      console.log('WebSocket connection closed');
      if (this.errorCallback) {
        this.errorCallback('WebSocket connection closed');
      }
    };

    return new Promise<void>((resolve, reject) => {
      if (!this.ws) {
        reject(new Error('WebSocket not initialized'));
        return;
      }

      this.ws.onopen = () => {
        console.log('WebSocket connection established');
        resolve();
      };
    });
  }

  onMessage(callback: (message: string) => void) {
    this.messageCallback = callback;
  }

  onError(callback: (error: string) => void) {
    this.errorCallback = callback;
  }

  onOpen(callback: () => void) {
    this.openCallback = callback;
  }

  async sendMessage(content: string | string[], user: string = '第三方', isContinue: boolean = false) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      throw new Error('WebSocket is not connected');
    }

    const message = {
      content,
      user,
      continue: isContinue
    };

    this.ws.send(JSON.stringify(message));
  }

  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

// 创建单例实例
export const dialogueAnalysisApi = new DialogueAnalysisWebSocket();
